<template>
	<view>
		<form @submit="formSubmit">
			<view class="cu-form-group">
				<view class="title">作物类型</view>
				<picker v-model="diagnose.cropType" name="cropType" @change="pickerChange" :value="cropTypeIndex" :range="cropTypeNameArr" disabled="true">
					<view class="picker">
						{{cropTypeIndex>-1?cropTypeNameArr[cropTypeIndex]:'选择作物种类'}}
					</view>
				</picker>
			</view>
			<view class="cu-form-group">
				<view class="title">部位</view>
				<picker v-model="diagnose.organName" name="organName" @change="pickerChangeOrgan" :value="organIndex" :range="organNameArr"  disabled="true">
					<view class="picker">
						{{organIndex>-1?organNameArr[organIndex]:'选择部位'}}
					</view>
				</picker>
			</view>
			<view class="cu-form-group">
				<view class="title">生长期</view>
				<picker v-model="diagnose.periodName" name="periodName" @change="pickerChangePeriod" :value="periodIndex" :range="periodNameArr"  disabled="true">
					<view class="picker">
						{{periodIndex>-1?periodNameArr[periodIndex]:'选择生长期'}}
					</view>
				</picker>
			</view>
			<view class="cu-form-group">
				<view class="title">发病日期</view>
				<picker  mode="date" :value="date" :start="startDate" :end="endDate"  @change="DateChange"  disabled="true">
					<view class="picker">
						{{date}}
					</view>
				</picker>
			</view>
			<view class="cu-form-group">
				<textarea   placeholder="症状描述" name="symptom" v-model="diagnose.symptom"  disabled="true"></textarea>
			</view>
			<view class="cu-form-group">
				<view class="action">
					病害图片
				</view>
				<view class="action">
					{{imgList.length}}/10
				</view>
			</view>
			<view class="cu-form-group">
				<view class="grid col-4 grid-square flex-sub">
					<view class="bg-img margin-top" v-for="(item,index) in imgList" :key="index" @tap="ViewImage" :data-url="imgList[index]">
					 <image :src="imgList[index]" mode="aspectFill"></image>
					</view>
				</view>
			</view>
			<view class="cu-bar bg-white solid-bottom margin-top">
				<view class="action">
					<text class="cuIcon-list text-blue"></text>诊断结果
				</view>
			</view>
			<view class="" v-if="resultList.length==0">
				<view class="padding text-center">
					<view class="padding-lr bg-white">
						<view class="padding">{{emptyResult}}</view>
					</view>
				</view>
			</view>
			<view v-for="(value, key) in resultList" :key="key" >
				<view class="cu-bar bg-white solid-bottom  solids-bottom">
					<view class="action">
						<text class="cuIcon-titles text-orange"></text> {{value.diagnoses}}
					</view>
				</view>
				<view class="cu-card case no-card" >
					<view class="cu-item shadow">
						<view class="solid-bottom text-sm padding">
							<view class="text-grey">
								<rich-text type="text" :nodes="value.solution"></rich-text>
							</view>
							<view class="padding flex flex-wrap justify-between align-center bg-white">
								<view class="title">诊断反馈:</view>
								<button class="cu-btn round sm" :class="value.helpful=='0'?'bg-red':''" @tap="feedbackResults(value.id,'0')">有帮助</button>
								<button class="cu-btn round sm" :class="value.helpful=='1'?'bg-red':''"  @tap="feedbackResults(value.id,'1')">无帮助</button>
							</view>
						</view>
					</view>
				</view>
			</view>
		</form>
	</view>
</template>

<script>
	var graceChecker = require("../../plugin/graceUI/jsTools/graceChecker.js");
	var graceRichText = require("../../plugin/graceUI/jsTools/richText.js");
	//获取日期
	function getDate(type) {
		const date = new Date();
	
		let year = date.getFullYear();
		let month = date.getMonth() + 1;
		let day = date.getDate();
	
		if (type === 'start') {
			year = year - 5;
		} else if (type === 'end') {
			year = year;
		}
		month = month > 9 ? month : '0' + month;;
		day = day > 9 ? day : '0' + day;
	
		return `${year}-${month}-${day}`;
	}
	export default {
		data() {
			return {
				//当前选择的开始时间
				imgindex: 0,
				date: getDate({
					format: true
				}),
				//时间选择限制条件-start
				startDate:getDate('start'),
				//时间选择限制条件-end
				endDate:getDate('end'),
				
				cropTypeIndex: 0,//作物种类
				cropTypeNameArr: [],
				cropTypeIdArr: [],
				organIndex: 0,//部位
				organNameArr: [],
				organIdArr:[],
				periodIndex: 0,//生长期
				periodNameArr: [],
				periodIdArr:[],

				diagnose:{//诊断
					id:'',
					userid:'',
					cropType:'',
					cropid:'',
					organName:'',
					periodid:'',
					periodName:'',
					organid:'',
					symptom:'',
					diseasepics:'',//上传后的相对路径
					diseasetime:''
				},
				imgList: [],//转换后的图像地址
				tempImgSrc: '',//当前要操作的图片路径，上传或者删除
				feedbackResultsUrl:this.$config.apiUrl+"/diseaseController/feedbackResults",
				resultList:[],//诊断结果
				emptyResult:'',
			};
		},
		onLoad: function (option) { //option为object类型，会序列化上个页面传递的参数
			if(option.id){
				this.diagnose.id=option.id;
			}else{
				this.diagnose.id="";
			}
			this.getDiagnose();
		},
		methods: {
			DateChange(e) {
				this.date = e.detail.value;
			},
			pickerChange(e) {
				this.cropTypeIndex = e.detail.value;
				this.diagnose.cropType=this.cropTypeNameArr[this.cropTypeIndex];
				this.diagnose.cropid=this.cropTypeIdArr[this.cropTypeIndex]
				this.organIndex=0;//重置部位
				this.getOrgan();
			},
			pickerChangeOrgan(e) {
				this.organIndex = e.detail.value;
				this.diagnose.organName=this.organNameArr[this.organIndex];
				this.diagnose.organid=this.organIdArr[this.organIndex];
			},
			pickerChangePeriod(e) {
				this.periodIndex = e.detail.value;
				this.diagnose.periodName=this.periodNameArr[this.periodIndex];
				this.diagnose.periodid=this.periodIdArr[this.organIndex];
			},
			
			//反馈信息
			feedbackResults(resultId,flag){
				let param={
					id:this.diagnose.id,
					helpful:flag,
					resultId:resultId//诊断结果id
				};
				this.$tip.loading();
				this.$http.post(this.feedbackResultsUrl,param).then(res=>{
					this.$tip.loaded();
					if (res.data.ok){
						let d=res.data.data;
						this.resultList=d.result;
						if(this.resultList.length==0){
							this.emptyResult="未能给出自动诊断!";
						}else{
							this.resultList.forEach((item,index)=>{
								item.solution = graceRichText.format(item.solution);
							});
						}
						//提示反馈信息
						this.$tip.toast(res.data.message);
					}
				}).catch(()=>{
					this.$tip.loaded();
					this.$tip.error('反馈信息失败！')
				});
				
			},
			
			//根据id获取信息
			getDiagnose(){
				var id='';
				if(this.diagnose.id==''){
					id='add_flag';//后台不允许id为空
				}else{
					id=this.diagnose.id
				}
				uni.request({
					url: this.$config.apiUrl+"/diseaseController/"+id,
					success: (res) => {
						// console.log(res);
						if(res.data.data!=null){
							this.diagnose=res.data.data;
							//图片
							let photoUrl=[];
							photoUrl=(this.diagnose.diseasepics==null || this.diagnose.diseasepics=="")?'':this.diagnose.diseasepics.split(",");
							for(var i=0;i<photoUrl.length;i++){
								if(photoUrl[i]!='' && photoUrl[i]!=null){
									var imgURL=this.$config.imgUrl+'/img/server/'+photoUrl[i];
									this.imgList.push(imgURL);
									this.tempImgSrc=photoUrl[i];
								}
							}
							
							this.cropTypeNameArr=this.diagnose.extMap.cropTypeNameArr;
							this.cropTypeIdArr=this.diagnose.extMap.cropTypeIdArr;
							this.cropTypeIdArr.forEach((item,index)=>{
								if(item==this.diagnose.cropid){
									this.cropTypeIndex=index;
								}
							});
							
							this.date=this.diagnose.diseasetime;
							
							this.getOrgan();
							this.getPeriod();
						}
					},
					fail: (res) => {
						uni.showToast({
						    title: "查询失败",
						    icon:"none"
						});
					},
					complete: () => {}
				});
			},
			//根据作物id获取部位
			getOrgan(){
				uni.request({
					url: this.$config.apiUrl+"/diseaseController/getOrgan",
					method: 'POST',
					header: {
						'content-type': 'application/x-www-form-urlencoded'//这样设置request才能接值
					},
					data: {
						cropid:this.cropTypeIdArr[this.cropTypeIndex]
					},
					success: (res) => {
						// console.log(res);
						if(res.data.data!=null){
							let organList=[];
							this.organNameArr=[];
							this.organIdArr=[];
							organList=res.data.data;
							// console.log(this.orgInfo.orgCode);\\
							organList.forEach((item,index)=>{
								this.organNameArr.push(item.name);
								this.organIdArr.push(item.id);
							});
							this.organIdArr.forEach((item,index)=>{
								if(item==this.diagnose.organid){
									this.organIndex=index;
								}
							});
						}
					},
					fail: (res) => {
						uni.showToast({
						    title: "查询失败",
						    icon:"none"
						});
					},
					complete: () => {}
				});
			},
			//根据作物id获取生长期
			getPeriod(){
				uni.request({
					url: this.$config.apiUrl+"/diseaseController/getPeriod",
					method: 'POST',
					header: {
						'content-type': 'application/x-www-form-urlencoded'//这样设置request才能接值
					},
					data: {
						cropid:this.cropTypeIdArr[this.cropTypeIndex]
					},
					success: (res) => {
						// console.log(res);
						if(res.data.data!=null){
							let periodList=[];
							this.periodNameArr=[];
							this.periodIdArr=[];
							periodList=res.data.data;
							// console.log(this.orgInfo.orgCode);\\
							periodList.forEach((item,index)=>{
								this.periodNameArr.push(item.name);
								this.periodIdArr.push(item.id);
							});
							this.periodIdArr.forEach((item,index)=>{
								if(item==this.diagnose.periodid){
									this.periodIndex=index;
								}
							});
						}
						
						this.getDiagnoseResult();
					},
					fail: (res) => {
						uni.showToast({
						    title: "查询失败",
						    icon:"none"
						});
					},
					complete: () => {}
				});
			},
			//获取诊断结果
			getDiagnoseResult(){
				uni.showLoading({
				    title: '诊断中...',
					mask: true
				});
				uni.request({
					url: this.$config.apiUrl+"/diseaseController/getDiagnoseResult",
					method: 'POST',
					header: {
						'content-type': 'application/x-www-form-urlencoded'//这样设置request才能接值
					},
					data: {
						diagnoseid:this.diagnose.id
					},
					success: (res) => {
						// console.log(res);
						if(res.data.data!=null){
							let d=res.data.data;
							this.resultList=d.result;
							if(this.resultList.length==0){
								this.emptyResult="未能给出自动诊断!";
							}else{
								this.resultList.forEach((item,index)=>{
									// item.diagnoses//诊断结果
									// item.solution//解决方案
									item.solution = graceRichText.format(item.solution);
								});
							}
						}
						uni.hideLoading();
					},
					fail: (res) => {
						uni.showToast({
						    title: "查询失败",
						    icon:"none"
						});
					},
					complete: () => {}
				});
			},
			ChooseImage() {
				uni.chooseImage({
					count: 10, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album'], //从相册选择
					success: (res) => {
						if (this.imgList.length != 0) {
							this.imgList = this.imgList.concat(res.tempFilePaths)
						} else {
							this.imgList = res.tempFilePaths
						}
						 this.tempImgSrc=res.tempFilePaths[0];
						 this.dealFile(1,0,'');
						 // for(let i=this.imgindex;i<this.imgList.length;i++,this.imgindex++){
						 // 	this.tempImgSrc = this.imgList[i];
						 // 	this.dealFile(1, 0, '');
						 // }
					}
				});
			},
			ViewImage(e) {
				uni.previewImage({
					urls: this.imgList,
					current: e.currentTarget.dataset.url
				});
			},
			DelImg(e) {
				uni.showModal({
					title: '删除照片',
					content: '确定要删除吗？',
					cancelText: '取消',
					confirmText: '确定',
					success: res => {
						if (res.confirm) {
							if(this.diagnose.id){
								let lj=this.imgList[e.currentTarget.dataset.index];
								let index=lj.indexOf("server");
								this.tempImgSrc=lj.substring(index+7,lj.length);
								this.dealFile(0,1,this.tempImgSrc);
							}
							this.imgList.splice(e.currentTarget.dataset.index, 1)
						}
					}
				})
			},
			//处理附件
			dealFile(isup,isdel,delPath){
				uni.uploadFile({
				    url: this.$config.apiUrl+"/appUploadController/dealFile",
					filePath: this.tempImgSrc,//当前要操作的图片路径，上传或者删除
					fileType: 'image',
					name: 'file',//后端通过'file'获取上传的文件对象
				    formData: {
						isup:isup,
						isdel:isdel,
						bizType:'photosucai',
						delPath:delPath
					},
				    success: (res) => {
						// console.log(res)
				        if (res.statusCode === 200) {
							let data=JSON.parse(res.data);
							let msg=data.message;
							if(isup==1){
								if(this.diagnose.diseasepics){
									this.diagnose.diseasepics+=','+data.data;
								}else{
									this.diagnose.diseasepics=data.data;
								}
							}else{
								//删除照片及逗号，三次匹配
								this.diagnose.diseasepics=this.diagnose.diseasepics.replace(','+delPath,'');
								this.diagnose.diseasepics=this.diagnose.diseasepics.replace(delPath+',','');
								this.diagnose.diseasepics=this.diagnose.diseasepics.replace(delPath,'');
							}
							// console.log(this.diagnose.photo);
				            uni.showToast({
				                title: msg,
								duration: 2000
				            });
							this.tempImgSrc="";
				        }
				    },
				    fail: (res) => {
				        console.log(res)
				    }
				});
			},
		}
	}
</script>

<style>
	.cu-form-group .title {
		min-width: calc(4em + 15px);
	}
	
</style>
